<?php

namespace App\Http\Middleware;

use App\Http\Controllers\Utils\ResponseFactory;
use Closure;
use Illuminate\Http\Request;

class ValidateOwnerResource
{
    /**
     * Handle an incoming request.
     * This middleware can compare auth's id with resourceId , if they are same then pase
     * Regular users only operate owner resource but root can operate everybody resource
     * @param \Illuminate\Http\Request $request
     * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
     * @return \Illuminate\Http\JsonResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $userId = auth()->user()->id;
        $ids = $request->all('id','userId','groupId');
        if ($userId === 1) {
            return $next($request);
        }
        foreach ($ids as $value){
            if (isset($value)&&$userId==$value){
                return $next($request);
            }
        }
        return  ResponseFactory::simpleResponse(false,"you don't operate other resource");
    }
}
